﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Models.Entity;

namespace Models
{
    public class DataDbContext : DbContext
    {
        private IConfiguration _configuration;
        /// <summary>
        /// 读取sqlserver连接字符串
        /// </summary>
        /// <returns></returns>
        public string SqlConnection()
        {
            // 创建ConfigurationBuilder对象
            var builder = new ConfigurationBuilder();
            builder.SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            // 构建IConfiguration对象
            _configuration = builder.Build();

            // 读取配置信息
            var connectionString = _configuration.GetSection("ConnectionStrings:sqlserver").Value;
            return connectionString;
        }

        public DataDbContext()
        {
        }
        public DataDbContext(DbContextOptions<DataDbContext> options)
        : base(options)
        {
        }
        public virtual DbSet<FaultNotice> NoticeEntities { get; set; }
        /// <summary>
        /// 配置DbContext需要的参数---例如 数据库连接字符串
        /// </summary>
        /// <param name="optionsBuilder"></param>
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                //mysql写法
                //var ConnectionString = "server = localhost; port = 3306; uid = root; pwd = 123456; database = dotnetcorewebapi";
                //var serverVersion = ServerVersion.AutoDetect("server = localhost; port = 3306; uid = root; pwd = 123456; database = dotnetcorewebapi");
                //optionsBuilder.UseMySql(ConnectionString, serverVersion);
                //sqlserver写法
                //192.168.8.211,1433
                //"Data Source= .;Initial Catalog = CZ_MES_Dashboard; User ID = sa; Password = 123456; TrustServerCertificate = true; Persist Security Info=True"
                optionsBuilder.UseSqlServer(SqlConnection());
            }
        }
        /// <summary>
        /// 配置数据库表映射关系
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //mysql写法
            //modelBuilder.UseCollation("utf8_general_ci").HasCharSet("utf8");
            modelBuilder.Entity<FaultNotice>(entity =>
            {
                entity.ToTable("FaultNotice").HasKey(u => u.ID);
                //entity.ToTable("UserInfo").HasIndex(u => u.UserId).IsUnique();  //唯一，不能重复
                //entity.Property(u => u.Title).HasDefaultValue("首页");  //给xx字段配置默认值
            });
        }
    }
}
